#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>
#include <QtCore>
#include <QtGui>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindowClass)
{
    ui->setupUi(this);
#ifdef MacOSX
    examFile = QDir::homePath() + QDir::separator() +"liu.exam";
#endif
#ifdef Windows
    examFile = QDir::currentPath() + QDir::separator() +"liu.exam";
#endif
    loadLiu();
    //設定題目類型
    {
        classifly.append(tr("Graphemic"));
        classifly.append(tr("Pronounce"));
        classifly.append(tr("Literalness"));
        classifly.append(tr("Number"));
        classifly.append(tr("English"));
        classifly.append(tr("Swing"));
        classifly.append(tr("Other"));
        classifly.append(tr("Not Used"));
    }

    ui->classification->addItems(classifly);

    //  加入跳轉的功能
    QLabel *index=new QLabel(tr("Jump:"));
    ui->mainToolBar->addWidget(index);
    indexBox = new QComboBox(this);
    ui->mainToolBar->addWidget(indexBox);
    //  新增Slot聯結
    connect(indexBox, SIGNAL(currentIndexChanged( int )),this,SLOT(gotoIndex()));
}
void MainWindow::gotoIndex()
{
    QString picName = etymonPics.value(indexBox->currentText()).first(); // 取得該項目的第一個圖檔
    saveItems(); //跳轉前 先存下目前的內容
    now = picList.indexOf(picName);
    ui->counts->setText(QString::number(now+1)+"/"+QString::number(picList.count()-1));
    showEtymonPic(picName);
    setItems(parserExam(examList.value(picName)));
}
MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_actionNext_triggered()
{
    if (! folderName.isEmpty())
        next();
}

void MainWindow::on_actionPrevious_triggered()
{
    if (! folderName.isEmpty())
        previous();
}

void MainWindow::next()
{
    QString picName;
    saveItems();
    now++;
    if (now > picList.count()-1)
    {
        picName = picList.first();
        now = 0;
    }
    else
    {
        picName = picList.at(now);
    }
    ui->counts->setText(QString::number(now+1)+"/"+QString::number(picList.count()));
    showEtymonPic(picName);
    setItems(parserExam(examList.value(picName)));
}
inline void MainWindow::showEtymonPic(const QString &name)
{
    QString picFileName = folderName + QDir::separator() + name;
    QPixmap p(picFileName);
    ui->etymon->setPixmap(p.scaled(40,40,Qt::KeepAspectRatio));
}
void MainWindow::previous()
{
    QString picName;
    saveItems();
    now--;
    if (now < 0)
    {
        picName = picList.last();
        now = picList.count()-1;
    }
    else
    {
        picName = picList.at(now);
    }
    ui->counts->setText(QString::number(now+1)+"/"+QString::number(picList.count()));
    showEtymonPic(picName);
    setItems(parserExam(examList.value(picName)));
}
bool MainWindow::loadLiu()
{

    QFile file(":/liu");
    if(! file.open(QIODevice::ReadOnly)){
        return false;
    }
    QMap<QString,QString> Unicode;
    QTextStream in(&file);
    in.readLine((qint64)80); //略過第一行
    while(!in.atEnd()){
            QString a = in.readLine((qint64)64);
            QString key = a.section("",0,5).simplified(),
                    word = a.section('~',1,1),
                    unicode = a.section('~',2,2);
            if(Unicode.contains(unicode))
            {
                QStringList tmp;
                tmp = dictionary.value(word);
                tmp << key;
                dictionary.insert(word,tmp);
            }
            else
            {
                Unicode.insert(unicode,word);
                QStringList tmp;
                tmp.append(key);
                dictionary.insert(word,tmp);
            }
        }
    file.close();
    return true;
}
bool MainWindow::loadImageFolder()
{
    folderName = QFileDialog::getExistingDirectory(this,tr("Open folder"),QDir::currentPath(),QFileDialog::ShowDirsOnly);
    QDir dir(folderName);
    QStringList filter;
    filter << "*.png";
    picList  = dir.entryList(filter,QDir::Files);

    foreach(QString str , picList)
    {
        // 依各個檔名的首字母分類
        QString initial = str.section("",0,1);
        QStringList tmp;
        if(etymonPics.contains(initial.toUpper()))
        {
            tmp = etymonPics.value(initial);
        }
        tmp.append(str);
        etymonPics.insert(initial.toUpper(),tmp);
        // 設定暫時的題目表;
        exam tempExam ;
        QStringList emptyList("");
        QString empty("");
        tempExam.pic = str;
        tempExam.exam = empty;
        tempExam.classify = empty;
        tempExam.etymon = empty;
        tempExam.etymonPics = emptyList;
        tempExam.explain = empty;
        tempExam.correct = empty;
        examList.insert(str,encoderExam(tempExam));
    }
    loadExam();
    return true;
}
QString MainWindow::encoderExam(const exam & set)
{
    return (set.pic+";"+set.exam+";"+set.classify+";"+set.etymon+";"+set.etymonPics.join("/")+";"+set.explain+";"+set.correct);
}
exam MainWindow::parserExam(const QString &line)
{
    exam set ;
    QStringList tempList = line.split(";");
    set.pic = tempList.at(0);
    set.exam = tempList.at(1);
    set.classify = tempList.at(2);
    set.etymon = tempList.at(3);
    set.etymonPics = tempList.at(4).split("/");
    set.explain = tempList.at(5);
    set.correct = tempList.at(6);
    return set;
}
bool MainWindow::loadExam()
{
    QFile file(examFile);
    if (! file.open(QIODevice::ReadOnly)){
		return false;
    }
    else{
        QTextStream in(&file);
        while(!in.atEnd()){
            QString line = in.readLine((qint64)512);
            exam test = parserExam(line);
            if (examList.contains(test.pic)){
                examList.insert(test.pic,line);
            }
            else
            {
                examList.insert(test.pic,line);
            }
        }
    }
    file.close();
    return true;
}
bool MainWindow::exportExam()
{
    saveItems();
    QFile file(examFile);
    if(! file.open(QIODevice::ReadWrite))
    {
		return false;
    }
    else
    {
        foreach(QString str , examList.keys()){
            QTextStream out(&file);
            out << examList.value(str) << endl ;
        }
    }
    file.close();
    return true;
}
void MainWindow::clearItems()
{
    ui->etymons->clear();
    ui->classification->setCurrentIndex(0);
    ui->etymon_1->clear();
    ui->etymon_2->clear();
    ui->etymon_3->clear();
    ui->etymon_4->clear();
    ui->etymon_5->clear();
    ui->lineEdit->clear();
    ui->lineEdit_2->clear();
    ui->lineEdit_3->clear();
}
void MainWindow::setItems(const exam &current)
{
    clearItems();
    if (! current.exam.isEmpty())
    {
        ui->lineEdit->setText(current.exam);
        QStringList tempEtymon = dictionary.value(current.exam);
        ui->etymons->clear();
        ui->etymons->addItems(tempEtymon);
        if (! current.etymon.isEmpty())
        {
            int index = tempEtymon.indexOf(current.etymon);
            ui->etymons->setCurrentIndex(index);
        }
        else
        {
            ui->etymons->setCurrentIndex(0);
        }
    }
    if (! current.classify.isEmpty())
    {
        int index = classifly.indexOf(current.classify);
        ui->classification->setCurrentIndex(index);
    }
    else
    {
        ui->classification->setCurrentIndex(0);
    }
    int stamp = 0;
    foreach(QString str,current.etymonPics){
        stamp ++;
        QString index = str.section("",0,1);
        if(!str.isEmpty()){
            switch(stamp){
                case 1:
                    ui->etymon_1->setCurrentIndex(etymonPics.value(index).indexOf(str));
                    break;
                case 2:
                    ui->etymon_2->setCurrentIndex(etymonPics.value(index).indexOf(str));
                    break;
                case 3:
                    ui->etymon_3->setCurrentIndex(etymonPics.value(index).indexOf(str));
                    break;
                case 4:
                    ui->etymon_4->setCurrentIndex(etymonPics.value(index).indexOf(str));
                    break;
                case 5:
                    ui->etymon_5->setCurrentIndex(etymonPics.value(index).indexOf(str));
                    break;
            }
        }
    }
    if (! current.explain.isEmpty())
    {
        ui->lineEdit_2->setText(current.explain);
    }
    if (! current.correct.isEmpty())
    {
        ui->lineEdit_3->setText(current.correct);
    }
}
void MainWindow::saveItems()
{
    exam word;
    QStringList tempList;
    {
        word.pic = picList.at(now);
        word.classify = ui->classification->currentText();
        word.exam = ui->lineEdit->text();
        word.etymon = ui->etymons->currentText();
	    // 囉唆的Pic 選單
        {
            for( int i = 0 ; i < word.etymon.size() ; i++)
            {
                QString temp = word.etymon.at(i);
                tempList << temp;
            }
            int stamp = 0 ;
            foreach(QString str , tempList)
            {
                stamp ++;
                if(!str.isEmpty())
                {
                    QString tempIndex;
                    switch(stamp)
                    {
                        case 1:
                            tempIndex = ui->etymon_1->currentText();
                            break;
                        case 2:
                            tempIndex = ui->etymon_2->currentText();
                            break;
                        case 3:
                            tempIndex = ui->etymon_3->currentText();
                            break;
                        case 4:
                            tempIndex = ui->etymon_4->currentText();
                            break;
                        case 5:
                            tempIndex = ui->etymon_5->currentText();
                            break;
                    }
                    word.etymonPics.append(tempIndex);
                }
            }
        }
        word.explain = ui->lineEdit_2->text();
        word.correct = ui->lineEdit_3->text();
        examList.insert(word.pic, encoderExam(word));
    }
}
void MainWindow::on_actionFolder_triggered()
{
    loadImageFolder();
    QString picFile = folderName + QDir::separator() + picList.at(0);
    QPixmap p(picFile);
    ui->etymon->setPixmap(p.scaled(40 ,40,Qt::KeepAspectRatio));
    now = 0;
    setItems(parserExam(examList.value(picList.at(0))));
    // 加入可供跳轉的項目
    indexBox->addItems(etymonPics.keys());
}
void MainWindow::on_lineEdit_textChanged(const QString &text)
{
        QStringList etymons = dictionary.value(text);
        ui->etymons->clear();
        ui->etymons->addItems(etymons);
}
void MainWindow::on_etymons_currentIndexChanged(const QString &text)
{
    QStringList c;
    for (int i = 0 ; i < text.size();i++)
    {
        QString z = text.at(i);
        c << z;
    }
    QDir dir(folderName);
    ui->etymon_1->clear();
    ui->etymon_2->clear();
    ui->etymon_3->clear();
    ui->etymon_4->clear();
    ui->etymon_5->clear();
    int stemp = 0 ;
    foreach(QString str , c){
        stemp ++ ;
        QStringList filter;
        filter << str + "*.png" ;
        QStringList pics  = dir.entryList(filter,QDir::Files);
        foreach(QString pic , pics){
            QPixmap p(folderName+ QDir::separator() + pic);
            QIcon icon;
            icon.addPixmap(p.scaled(40,40,Qt::KeepAspectRatio));
            switch(stemp){
                case 1:
                    ui->etymon_1->addItem(icon,pic);
                    break;
                case 2:
                    ui->etymon_2->addItem(icon,pic);
                    break;
                case 3:
                    ui->etymon_3->addItem(icon,pic);
                    break;
                case 4:
                    ui->etymon_4->addItem(icon,pic);
                    break;
                case 5:
                    ui->etymon_5->addItem(icon,pic);
                    break;
            }
        }
    }
}
void MainWindow::on_actionExport_Exam_triggered()
{
    if(!folderName.isEmpty())
        exportExam();
}
void MainWindow::on_actionSet_ExamFile_triggered()
{
    examFile = QFileDialog::getOpenFileName(this,
                                            tr("give a file locate"),
                                            QDir::rootPath());
}
